# -*- coding: utf-8 -*-

"""
Python 线程池和并发锁示例
"""

import threading
import time
from concurrent.futures import ThreadPoolExecutor

# 3. 线程池和并发锁 (ThreadPool and Locks)
print("\n======== 3. 线程池和并发锁 ========")

shared_resource = 0
lock = threading.Lock()

def update_shared_resource():
    global shared_resource
    with lock:
        # 使用锁来保护共享资源
        current_value = shared_resource
        time.sleep(0.1)  # 模拟耗时操作
        shared_resource = current_value + 1

with ThreadPoolExecutor(max_workers=5) as executor:
    # 提交10个任务到线程池
    for _ in range(10):
        executor.submit(update_shared_resource)

print(f"未使用锁的情况下，共享资源的值可能小于10。")
print(f"使用锁之后，最终共享资源的值: {shared_resource}")

def run_tests():
    # 测试线程池和锁
    # 重新运行线程池逻辑以进行测试
    global shared_resource
    shared_resource = 0
    with ThreadPoolExecutor(max_workers=5) as executor:
        for _ in range(10):
            executor.submit(update_shared_resource)
    assert shared_resource == 10
    print("线程池和并发锁测试通过!")

if __name__ == "__main__":
    run_tests()